package com.clf.springBoot.modules.common.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: chenglongfei
 * @date: 2022/7/12
 * @Description ExceptionController
 */
@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(value = {Exception.class})
    public ModelAndView handleException(HttpServletRequest request,Exception ex ){

       //初始化返回数据
        HttpStatus httpStatus=HttpStatus.OK;
        String message="";
        String data="";

        //根据异常的类型。包装返回数据
        if (ex instanceof UnauthenticatedException){
            httpStatus=HttpStatus.FORBIDDEN;
            message="没有权限";
            data="/common/403";
        }else {
            httpStatus=HttpStatus.INTERNAL_SERVER_ERROR;
            message="内部错误";
            data="/common/500";
        }

        if (isInterface(request)){
            return returnJson(httpStatus,message,data);
        }else {
            return returnPage(data,httpStatus);
        }
    }
    //判断是否为接口
    private boolean isInterface(HttpServletRequest request){
        HandlerMethod handlerMethod= (HandlerMethod) request.getAttribute(
                "org.springframework.web.servlet.HandlerMapping.bestMatchingHandler");
        RestController[] annotations1=handlerMethod.getBeanType().getAnnotationsByType(RestController.class);
        ResponseBody[] annotations2=handlerMethod.getBeanType().getAnnotationsByType(ResponseBody.class);
        ResponseBody[] annotations3=handlerMethod.getMethod().getAnnotationsByType(ResponseBody.class);

        return annotations1.length>0 || annotations2.length>0 ||annotations3.length>0;


    }

    //返回页面
    public ModelAndView returnPage(String data,HttpStatus httpStatus){
        return  new ModelAndView(new RedirectView(data));
    }

    //返回json 数据
    public ModelAndView returnJson(HttpStatus httpStatus,String message,String data){
        ModelAndView modelAndView=new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("status",httpStatus.value());
        modelAndView.addObject("message",message);
        modelAndView.addObject("data",data);
        return modelAndView;
    }
}
